package com.syni.mdd.sjb.tool.utils;

import com.syni.mdd.sjb.common.component.utils.common.utils.StringUtils;
import com.syni.mdd.sjb.common.component.utils.redis.utils.RedisTemplateUtils;
import com.syni.mdd.sjb.tool.constants.Constants;

import java.util.concurrent.TimeUnit;
public class VerificationCodeUtils {

    public static String VerificationCodeRedisKeyPrefix = "sjb:tool:verificationCode";
    public static String SJB_LOGIN_CODE_PREFIX = "dsApi:identifyCode:203:";

    public static void addVerificationCode(Integer channel,String phone,Integer codeType,String codeValue){
        String key = String.format("%s:%s:%s:%s",VerificationCodeRedisKeyPrefix,channel,phone,codeType);
        RedisTemplateUtils.getRedisTemplate().opsForValue().set(key,codeValue,5, TimeUnit.MINUTES);
        //兼容以前数据宝的登录验证码
        if(channel == Constants.VERT_CODE_CHANNEL && codeType == Constants.VERT_CODE_TYPE_10){
            RedisTemplateUtils.getRedisTemplate().opsForValue().set(SJB_LOGIN_CODE_PREFIX + phone,codeValue,5, TimeUnit.MINUTES);
        }
    }

    public static boolean checkVerificationCode(Integer channel,String phone,Integer codeType,String codeValue){
        String key = String.format("%s:%s:%s:%s",VerificationCodeRedisKeyPrefix,channel,phone,codeType);
        if(RedisTemplateUtils.getRedisTemplate().hasKey(key)){
            String identifyCode = RedisTemplateUtils.getRedisTemplate().opsForValue().get(key).toString();
            if(StringUtils.isNotBlank(identifyCode) && identifyCode.equals(codeValue)){
                RedisTemplateUtils.delete(key);
                return true;
            }
        }
        return false;
    }

    public static String getVerificationCode() {
        StringBuilder stringBuilder = new StringBuilder();
        for(int ii = 0;ii < 6;ii++){
            int code = (int)(Math.random() * 10);
            stringBuilder.append(code);
        }
        return stringBuilder.toString();
    }
}
